package com.wchat.server.handler;

import com.wchat.server.codec.WsMessageCodec;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author : willian fu
 * @date : 2020/5/30
 */
@Slf4j
@Component
@NoArgsConstructor
public class WsChildHandler extends ChannelInitializer<NioSocketChannel> {

    @Autowired
    private WsMessageCodec wsMessageCodec;

    @Autowired
    private MessageHandler messageHandler;

    @Autowired
    private WebSocketHandHandler handHandler;

    @Override
    protected void initChannel(NioSocketChannel channel) throws Exception {
        channel.pipeline()
                //.addLast(new HeartbeatHandler())
                //websocket协议本身是基于http协议的，所以这边也要使用http解编码器
                .addLast(new HttpServerCodec())
                //以块的方式来写的处理器
                .addLast(new ChunkedWriteHandler())
                //netty是基于分段请求的，HttpObjectAggregator的作用是将请求分段再聚合,参数是聚合字节的最大长度
                .addLast(new HttpObjectAggregator(1024 * 100))
                //握手部分协议处理
                .addLast(handHandler)
                //ws://localhost:8899/ws
                .addLast(new WebSocketServerProtocolHandler("/wchat", null, true, 65536))
                //websocket定义了传递数据的6中frame类型
                .addLast(wsMessageCodec)
                .addLast(messageHandler);
    }
}
